//
//  KeRenBleTool.m
//  KEREN
//
//  Created by MW on 2023/3/14.
//

#import "KeRenBleTool.h"
@interface KeRenBleTool()
@end

@implementation KeRenBleTool

+(instancetype)sharedInstance{
    static KeRenBleTool *keRenBleTool = nil;
    if (keRenBleTool == nil) {
        keRenBleTool = [[KeRenBleTool alloc] init];
    }
    return keRenBleTool;
}

//扫描并连接蓝牙	
+ (void)scanAndConnectedBLE:(NSString *)sn_cond callBack:(void (^)(BOOL success))callback{
    WEAKSELF
    DDLogInfo(@"=======bleConnected characteristic is: 015");
    [[HABleManager sharedManager] scanPeriperals:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, NSDictionary<NSString *,id> * _Nonnull advertisementData, NSNumber * _Nonnull RSSI) {
//        DDLogInfo(@"=====扫描到设备 peripheral.name is :%@",peripheral.name);
        if([peripheral.name containsString: [sn_cond substringFromIndex:sn_cond.length-4]]){
            DDLogInfo(@"=====扫找到目标设备2 peripheral.name is :%@",peripheral.name);
            peripheral.snCode = sn_cond;
            peripheral.authorized = @(NO);
            [[HABleManager sharedManager] stopScanPeriperals];
//            DDLogInfo(@"=======bleConnected characteristic is: 013");
//            [KeRenBleTool bleConnected:peripheral callBack:callback];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                DDLogInfo(@"=======bleConnected characteristic is: 013");
                [weakSelf bleConnected:peripheral callBack:callback];
            });
        }
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[HABleManager sharedManager] stopScanPeriperals];
    });
}

+ (void)bleConnected:(CBPeripheral *)peripheral callBack:(void (^)(BOOL success))callback{
    [HABleManager sharedManager].currentPeri = peripheral;
    DDLogInfo(@"=======bleConnected characteristic is: 011");
    [[HABleManager sharedManager] connectToPeripheral:peripheral success:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral) {
        if(callback != nil)callback(YES);
        DDLogInfo(@"=======bleConnected characteristic is: 01");
    } fail:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
        if(callback != nil)callback(NO);
        DDLogInfo(@"=======bleConnected characteristic is: 02");
        [[KRAlartManager shareInstance] showAlert:@"请前往设置查看是否已配对并忽略"];
    } characteristic:^(CBPeripheral * _Nonnull peripheral, CBService * _Nonnull service, NSError * _Nonnull error) {
//        if(callback != nil)callback(NO);
        DDLogInfo(@"=======bleConnected characteristic is:%@",error);
    }];
}


@end
